<template>
  <canvas :id="canvasId" ref="borderRef" class="border-canvas" :width="width" :height="height"></canvas>
</template>
<script>
import { Border } from '@/utils/animation'
import { pick } from 'lodash'

export default {
  name: 'ShowBorder',
  props: {
    borderAttrs: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {}
  },
  computed: {
    canvasId() {
      return `border-canvas-${this.borderAttrs.id}`
    },
    width() {
      return this.borderAttrs.width
    },
    height() {
      return this.borderAttrs.height
    },
  },
  watch: {
    borderAttrs: {
      deep: true,
      handler(newVal) {
        if (JSON.stringify(newVal) !== this?.oldBorderAttrs) {
          this.border
            && this.border.setParamsToInit({
              ...pick(newVal, ['borderType', 'borderSpeed', 'borderEffect', 'borderSW', 'width', 'height']),
            })
        }
        this.oldBorderAttrs = JSON.stringify(newVal)
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initBorder()
    })
  },
  beforeDestroy() {
    this.border && this.border.dispose()
  },
  methods: {
    initBorder() {
      if (!this.border) {
        this.border = new Border({
          ...this.borderAttrs,
          canvasDom: this.$refs.borderRef,
        })
        this.border.init()
      }
    },
  },
}
</script>
<style scoped lang="scss">
.border-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
